package WriteOutputs;


use Exporter qw( import );
our @EXPORT = qw( create_post_details_file create_metadata_file create_categories_summary_page );

use utf8;
use Time::Piece;

sub Unindent {
        my ($val) = @_;
        $val =~ s/^(\s*\n)//gs;
        $val =~ s/(\n)([ \t]*\n)?\s*$/$1/gs;
        my ($space) = ($val =~ /^(\s+)/);
        $val =~ s/^$space//gm;
        return $val;
}

my $HTML_HEADER = qq(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />);
my $FOOTER = qq(<div id="footer" class="footer">Copyright © <script language="JavaScript" type="text/javascript">document.write((new Date()).getFullYear());</script> எழுத்தாளர் ஜெயமோகன் </div>\n);


sub create_post_details_file {
	
	my ($url, $file_name, $post_title, $post_categories, $post_tags, $post_contents, $word_count) = @_;

	# TODO: Do this the right way. Create a directory dynamically.
	open my $POST_DETAILS_FILE, '>:encoding(UTF-8)', $file_name
		or croak $url.": Unable to open ".$file_name." for writing";

	print {$POST_DETAILS_FILE} $HTML_HEADER;

	print {$POST_DETAILS_FILE} qq(<html>\n<body>\n);

	my $stylesheet = qq(<link rel="stylesheet" href="../../css/archived-page.css" type="text/css" media="screen, projection">\n);

	my $title = qq[<div class="title"> $post_title <p class="metadata"> ($word_count words)</p>\n</div>\n];

	print {$POST_DETAILS_FILE} $stylesheet, "\n", $title, "\n";

	print {$POST_DETAILS_FILE} qq(<div class="post-container">\n $$post_contents\n);
	print {$POST_DETAILS_FILE} qq(<div class = "push"></div>\n</div>\n);
	print {$POST_DETAILS_FILE} $FOOTER, "\n";
	print {$POST_DETAILS_FILE} "</body>\n</html>\n";

	close($POST_DETAILS_FILE);
}



sub create_metadata_file {
	
	my ($url, $file_name, $post_title, $post_categories, $post_tags, $word_count, $year_month) = @_;

	# TODO: Do this the right way. Create a directory dynamically.
	open my $POST_METADATA_FILE, '>:encoding(UTF-8)', $file_name
		or croak $url.": Unable to open ".$file_name." for writing";

	print {$POST_METADATA_FILE} $url."|";
	print {$POST_METADATA_FILE} $post_title."|";
	print {$POST_METADATA_FILE} $year_month."|";
	print {$POST_METADATA_FILE} join(', ',@{$post_categories})."|";
	print {$POST_METADATA_FILE} join(', ', @{$post_tags});

	close($POST_METADATA_FILE);
}




sub create_categories_summary_page {
	
	my ($categories, $file_name) = @_;

	# TODO: Do this the right way. Create a directory dynamically.
	open my $CATEGORIES_FILE, '>:encoding(UTF-8)', $file_name
		or croak $url.": Unable to open ".$file_name." for writing";

	print {$CATEGORIES_FILE} $HTML_HEADER;
	print {$CATEGORIES_FILE} qq(<link rel="stylesheet" href="../css/categories-summary.css" type="text/css" media="screen, projection"> <div class="categories-container">);

	binmode(STDOUT, ':utf8');
	my $count = 1;
	foreach my $category (keys %{ $categories }) {
		$category =~ s/^\s+|\s+$//g;
		
		my @urls_and_titles = split(/\|/, $categories->{$category});
		my $filename = "../output/category/". $count.".htm";
		
		create_urls_for_category_page($category, $filename, \@urls_and_titles);

		$count++;

		my $posts_count = scalar(@urls_and_titles);
		my $category_id = '';
		
		# Horrible code warning. For creating the tag cloud like font sizes, 
		# split the post counts into buckets and create CSS classes for each bucket.
		if ($posts_count >= 2000) 		{ $category_id = 'categories-2k'; }
		elsif ($posts_count >= 1000) 	{ $category_id = 'categories-1k'; }
		elsif ($posts_count >= 500) 	{ $category_id = 'categories-500'; }
		elsif ($posts_count >= 250 )	{ $category_id = 'categories-250'; }
		elsif ($posts_count >= 125)		{ $category_id = 'categories-125'; }
		else  							{ $category_id = 'categories'; }

		print {$CATEGORIES_FILE} Unindent(qq(<div id="$category_id" class="categories"> <a href="$filename">$category<font class="count"> ($posts_count)</font></a></div>\n));
	}
	
	#TODO: This is a dummy <div> to push create a gap between the end of the post and footer
	# Not sure how effective this is. Might remove it after some tests.
	
	print {$CATEGORIES_FILE} qq(<div class = "push"></div>\n</div>\n);
	print {$CATEGORIES_FILE} $FOOTER, "\n", qq(</head></html>);

	close($CATEGORIES_FILE);
}




sub create_urls_for_category_page {
	my ($category, $filename, $urls_and_titles) = @_;

	open my $CATEGORY_FILE, '>:encoding(UTF-8)', $filename
		or croak $url.": Unable to open ".$filename." for writing";

	my $count = scalar(@{$urls_and_titles});
	my $urls_per_card = 25;
	my $number_of_cards = int($count / $urls_per_card) + 1;
	
	my $start = 0;
	my $end = $urls_per_card;
	

	print {$CATEGORY_FILE} $HTML_HEADER;
	print {$CATEGORY_FILE} qq(<link rel="stylesheet" href="../../css/posts_under_a_category.css" type="text/css" media="screen, projection">\n);
	print {$CATEGORY_FILE} qq(<title>$category</title>\n <body>\n);
	print {$CATEGORY_FILE} qq(<section class="gallery">\n);

	my $serial_number = 1;
	for(my $i = 0; $i < $number_of_cards; $i++) {
		print {$CATEGORY_FILE} qq(<div class="card">\n);
 		
 		if ($count < $urls_per_card ) {
 			$end = $count;
 		}

 		foreach $entry (@{$urls_and_titles}[$start .. ($end - 1)]) {
			my ($url, $title, $year_month) = split(/~/, $entry);
			
			my $t = Time::Piece->strptime($year_month, "%Y%m");
			my $year_month_formatted = $t->month."-".$t->year;
			
			print ${CATEGORY_FILE} qq(<div class="row">
										<font class="sno">$serial_number. </font>
										<a class="permalink" href="$url">$title</a>
										<font class="year-month">($year_month_formatted)</font>
									</div>\n);
			$serial_number++;
		}
		
		$start = $end;
		$end += $urls_per_card;

		if($end > $count) {
 			$end = $count; 
 		}
		print ${CATEGORY_FILE} "</div>\n"; # class = "card"
	}

	print {$CATEGORY_FILE} "</section>\n";
	print {$CATEGORY_FILE} $FOOTER;
	print {$CATEGORY_FILE} "</body></head></html>";
	
	close($CATEGORY_FILE);
}